// pages/personalUpload/personalUpload.js
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isDetails:false,
    id: '',
    name: '',
    idCardNo: '',
    sexArray: [{
        name: '男',
        value: '1',
        checked: 'true'
      },
      {
        name: '女',
        value: '2',
      }
    ],
    sex: '1',
    phone: '',
    domicile: '',
    address: '',
    region: ['广东省', '广州市', '海珠区'],
    cfRegion: ['广东省', '广州市', '海珠区'],
    cfAddress: '',
    mdRegion: ['广东省', '广州市', '海珠区'],
    mdAddress: '',
    trafficToolArray: ['火车', '飞机', '自驾车'],
    trafficToolIndex: 0,
    vehicleNub: '',
    vehicleInfo: '',
    trainDate: '2019-09-01',
    accompanyingArray: [{
      'name': ''
    }],
    emergencyContactArray: [{
      'name': '',
      'phone': ''
    }],
    seleCheckitems: [],
    checkitems: [{
        name: '1',
        value: 'A.14天内，在湖北省居住过或进入过湖北省境内'
      },
      {
        name: '2',
        value: 'B.14天内，接触过来自湖北省的人员'
      },
      {
        name: '3',
        value: 'C.14天内，接触过本地发热病人'
      },
      {
        name: '4',
        value: 'D.14天内，本人是否出现过发热、乏力、干咳症状'
      },
      {
        name: '5',
        value: 'E.现在是否有一下症状1、发热(体温高于37.3度2、乏力3、干咳4、其他'
      },
    ],
    imageArray: [],
    imagePathArray: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {


    if (options.id != '0') {
      this.setData({
        id: options.id
      })
      this.loadData();
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  loadData: function() {

    var that = this;
    wx.request({
      url: getApp().BASE_URL + '/gr/getGrPeople',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      method: 'POST',
      data: {
        openid: getApp().globalData.openId,
        id: that.data.id
      },
      success: function(res) {
        console.log(res)
        if (res.data.code == 200) {
          var model = res.data.data;
          var sexArray = that.data.sexArray;
          if (model.sex == '1') {
            var sexModel = sexArray[0];
            sexModel.checked = true;
            var sexModel1 = sexArray[1];
            sexModel1.checked = false;

          } else {
            var sexModel = sexArray[0];
            sexModel.checked = false;
            var sexModel1 = sexArray[1];
            sexModel1.checked = true;

          }

          //问题
          var checkitems = that.data.checkitems;
          if (model.situation == '是') {
            checkitems[0].checked = 'true'
          }
          if (model.situation1 == '是') {
            checkitems[1].checked = 'true'
          }
          if (model.situation2 == '是') {
            checkitems[2].checked = 'true'
          }
          if (model.situation3 == '是') {
            checkitems[3].checked = 'true'
          }
          if (model.situation4 == '是') {
            checkitems[4].checked = 'true'
          }

          //联系人
          var newCompanionArray = []
          if (model.companion.length != 0) {
            var modelArray = model.companion.split(',')
            for (var i = 0; i < modelArray.length; i++) {
              var lianxiren = {};
              lianxiren.name = modelArray[i];
              newCompanionArray.push(lianxiren)
            }
          }else {
            newCompanionArray = that.data.accompanyingArray;
          }

          var newEmergencyContactArray = []
          if(model.jjName.length > 0) {
            var jj = {}
            jj.name = model.jjName;
            jj.phone = model.jjPhone;
            newEmergencyContactArray.push(jj)
          }else {
            newEmergencyContactArray = that.data.emergencyContactArray;
          }
          
          if (model.jjName1.length > 0) {
            var jj = {}
            jj.name = model.jjName1;
            jj.phone = model.jjPhone1;
            newEmergencyContactArray.push(jj)
          }


          //图片
          var newImageArray = []
          if (model.file.length != 0) {
            var imageArray = model.file.split(',')
            for (var i = 0; i < imageArray.length; i++) {
              var data = imageArray[i]
              var str = getApp().BASE_URL + data
              newImageArray.push(str)
            }

          }

          that.setData({
            model:model,
            isDetails:true,
            name: model.name,
            sexArray: sexArray,
            sex: model.sex,
            idCardNo: model.idcard,
            phone: model.phone,
            region: [model.hjArea, model.hjArea1, model.hjArea2],
            address: model.hjArea3,
            trafficToolIndex: model.vehicleType - 1,
            trainDate: model.vehicleDate,
            vehicleNub: model.vehicleNub,
            vehicleInfo: model.vehicleInfo,
            cfRegion: [model.cfArea, model.cfArea1, model.cfArea2],
            cfAddress: model.cfArea3,
            mdRegion: [model.mdArea, model.mdArea1, model.mdArea2],
            mdAddress: model.mdArea3,
            accompanyingArray: newCompanionArray,
            emergencyContactArray:newEmergencyContactArray,
            checkitems: checkitems,
            imagePathArray: newImageArray
          })

        }
      },
      fail: function(res) {

      },
      complete: function(res) {
        wx.hideLoading();
      }
    })

  },

  /**
   * 更新数据
   */
  updateInputValue: function(res) {

    var that = this;
    console.log(res);
    let valueName = res.target.dataset.name;
    let value = res.detail.value;
    that.data[valueName] = value;

  },

  /**
   * 更新性别
   */
  updateSexValue: function(res) {

    this.setData({
      sex: res.detail.value
    })

  },

  /**
   * 更新户籍地
   */
  bindRegionChange: function(e) {
    console.log(e)
    var name = e.target.dataset.name;
    if (name == 'region') {
      this.setData({
        region: e.detail.value
      })
    }
    if (name == 'cfRegion') {
      this.setData({
        cfRegion: e.detail.value
      })
    }
    if (name == 'mdRegion') {
      this.setData({
        mdRegion: e.detail.value
      })
    }

  },

  /**
   * 更新交通工具
   */
  bindPickerChange: function(e) {

    this.setData({
      trafficToolIndex: e.detail.value
    })
  },

  /**
   * 时间选择器
   */
  bindDateChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      trainDate: e.detail.value
    })
  },

  /**
   * 添加随行人员
   */
  addAccompanying: function(e) {

    var that = this;
    if (that.data.accompanyingArray.length >= 6) {
      wx.showToast({
        title: '最多添加6个随行人员',
        icon: 'none',
        duration: 1500
      })
      return;
    }

    var accompanyingS = that.data.accompanyingArray;
    accompanyingS.push({
      'name': ''
    });
    that.setData({
      accompanyingArray: accompanyingS
    })

  },

  /**
   * 添加随行人员数据更新
   */
  accompanyingUpdateInputValue: function(e) {

    var that = this;
    var index = e.target.dataset.index;
    var model = that.data.accompanyingArray[index];
    model.name = e.detail.value;

  },

  /**
   * 添加紧急联系人
   */
  addEmergencyContact: function(e) {

    var that = this;
    if (that.data.emergencyContactArray.length >= 2) {
      wx.showToast({
        title: '最多添加2个紧急联系人',
        icon: 'none',
        duration: 1500
      })
      return;
    }

    var mergencyContactS = that.data.emergencyContactArray;
    mergencyContactS.push({
      'name': '',
      'phone': ''
    });
    that.setData({
      emergencyContactArray: mergencyContactS
    })

  },

  /**
   * 紧急联系人名字
   */
  emergencyContactNameUpdateInputValue: function(e) {

    var that = this;
    var index = e.target.dataset.index;
    var model = that.data.emergencyContactArray[index];
    model.name = e.detail.value;

  },

  /**
   * 紧急联系人名字
   */
  emergencyContactPhoneUpdateInputValue: function(e) {

    var that = this;
    var index = e.target.dataset.index;
    var model = that.data.emergencyContactArray[index];
    model.phone = e.detail.value;

  },

  /**
   * 添加图片
   */
  addImageBtnClick() {
    var that = this;
    if (that.data.imageArray.length >= 6) {

      wx.showToast({
        title: '最多选择四张图片',
        icon: 'none'
      })
      return;
    }

    var pics = that.data.imageArray;
    wx.chooseImage({
      count: 6 - pics.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) { // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        that.setData({
          imageArray: pics.concat(tempFilePaths)
        })
      }
    })
  },

  /**
   * 预览图集
   */
  previewImage(e) {

    var that = this
    var index = e.currentTarget.dataset.index;
    wx.previewImage({
      current: that.data.imageArray[index],
      urls: that.data.imageArray

    });
  },

  /**
   * 预览图集
   */
  previewImageDetails(e) {

    var that = this
    var index = e.currentTarget.dataset.index;
    wx.previewImage({
      current: that.data.imagePathArray[index],
      urls: that.data.imagePathArray

    });
  },

  /**
   * 删除图片
   */
  deleteImage(e) {
    var that = this
    var index = e.currentTarget.dataset.index;
    var imageArray = that.data.imageArray
    imageArray.splice(index, 1);
    that.setData({
      imageArray: imageArray
    })
  },

  /**
   * 多选事件
   */
  checkboxChange: function(e) {

    var that = this;
    that.data.seleCheckitems = e.detail.value;

  },

  /**
   * 提交时间
   */
  submitClick: function(e) {


    var that = this;
    var name = that.data.name;
    var sex = that.data.sex;
    var idcard = that.data.idCardNo;
    var phone = that.data.phone;
    var hjArea = that.data.region[0];
    var hjArea1 = that.data.region[1];
    var hjArea2 = that.data.region[2];
    var hjArea3 = that.data.address;
    var vehicleType = parseInt(that.data.trafficToolIndex) + 1;
    var vehicleDate = '';
    var vehicleNub = '';
    var vehicleInfo = '';
    if (vehicleType == 1) {
      vehicleDate = that.data.trainDate;
      vehicleNub = that.data.vehicleNub;
      vehicleInfo = that.data.vehicleInfo;
    } else if (vehicleType == 2) {
      vehicleDate = that.data.trainDate;
      vehicleNub = that.data.vehicleNub;
      vehicleInfo = that.data.vehicleInfo;
    } else {
      vehicleInfo = that.data.vehicleInfo;
    }
    var cfArea = that.data.cfRegion[0];
    var cfArea1 = that.data.cfRegion[1];
    var cfArea2 = that.data.cfRegion[2];
    var cfArea3 = that.data.cfAddress;

    var mdArea = that.data.mdRegion[0];
    var mdArea1 = that.data.mdRegion[1];
    var mdArea2 = that.data.mdRegion[2];
    var mdArea3 = that.data.mdAddress;

    var companion = '';
    for (var i = 0; i < that.data.accompanyingArray.length; i++) {
      var model = that.data.accompanyingArray[i];
      if (model.name != '') {
        companion += model.name;
        if (i != that.data.accompanyingArray.length - 1) {
          companion += ','
        }
      }
    }

    var jjName = that.data.emergencyContactArray[0].name;
    var jjPhone = that.data.emergencyContactArray[0].phone;
    var jjName1 = '';
    var jjPhone1 = '';
    if (that.data.emergencyContactArray.length > 1) {
      jjName = that.data.emergencyContactArray[1].name;
      jjPhone = that.data.emergencyContactArray[1].phone;
    }

    var situation = '否';
    var situation1 = '否';
    var situation2 = '否';
    var situation3 = '否';
    var situation4 = '否';
    //13282828177
    for (var i = 0; i < that.data.seleCheckitems.length; i++) {
      var situationModle = parseInt(that.data.seleCheckitems[i]);
      if (situationModle == 1) {
        situation = '是';
      }
      if (situationModle == 2) {
        situation1 = '是';
      }
      if (situationModle == 3) {
        situation2 = '是';
      }
      if (situationModle == 4) {
        situation3 = '是';
      }
      if (situationModle == 5) {
        situation4 = '是';
      }

    }


    if (that.data.name.length == 0) {
      that.showErroMessage('请输入您的姓名');
      return;
    }

    if (that.data.idCardNo.length == 0) {
      that.showErroMessage('请输入您的证件号');
      return;
    }

    if (that.data.phone.length == 0) {
      that.showErroMessage('请输入您的手机号');
      return;
    }

    if (that.data.address.length == 0) {
      that.showErroMessage('请输入您的详细地址');
      return;
    }

    if (vehicleType == 1) {
      if (vehicleDate.length == 0) {
        that.showErroMessage('请选择您的出发时间');
        return;
      }
      if (vehicleNub.length == 0) {
        that.showErroMessage('请输入您乘坐的车次');
        return;
      }
      if (vehicleInfo.length == 0) {
        that.showErroMessage('请输入您乘坐的座位号');
        return;
      }
    }


    if (vehicleType == 2) {
      if (vehicleDate.length == 0) {
        that.showErroMessage('请选择您的出发时间');
        return;
      }
      if (vehicleNub.length == 0) {
        that.showErroMessage('请输入您乘坐的航班');
        return;
      }
      if (vehicleInfo.length == 0) {
        that.showErroMessage('请输入您乘坐的座位号');
        return;
      }
    }

    if (vehicleType == 3) {
      if (vehicleInfo.length == 0) {
        that.showErroMessage('请输入您的车牌号');
        return;
      }
    }

    if (cfArea3.length == 0) {
      that.showErroMessage('请输入出发地的详细地址');
      return;
    }

    if (mdArea3.length == 0) {
      that.showErroMessage('请输入目的地的详细地址');
      return;
    }

    //开始上传图片

    //将所有数据包装
    var model = {};
    model.name = name;
    model.sex = sex;
    model.idcard = idcard;
    model.phone = phone;
    model.hjArea = hjArea;
    model.hjArea1 = hjArea1;
    model.hjArea2 = hjArea2;
    model.hjArea3 = hjArea3;
    model.vehicleType = vehicleType;
    model.vehicleDate = vehicleDate;
    model.vehicleNub = vehicleNub;
    model.vehicleInfo = vehicleInfo;
    model.companion = companion;
    model.jjName = jjName;
    model.jjPhone = jjPhone;
    model.jjName1 = jjName1;
    model.jjPhone1 = jjPhone1;
    model.situation = situation;
    model.situation1 = situation1;
    model.situation2 = situation2;
    model.situation3 = situation3;
    model.situation4 = situation4;
    model.cfArea = cfArea;
    model.cfArea1 = cfArea1;
    model.cfArea2 = cfArea2;
    model.cfArea3 = cfArea3;
    model.mdArea = mdArea;
    model.mdArea1 = mdArea1;
    model.mdArea2 = mdArea2;
    model.mdArea3 = mdArea3;
    model.openid = getApp().globalData.openId;
    //上传图片
    var imageArray = that.data.imageArray
    if (imageArray.length != 0) {
      wx.showLoading({
        title: '正在上传,请耐心等待',
      })
      for (var i = 0; i < imageArray.length; i++) {
        var imageSrc = imageArray[i];
        (function(index) {
          wx.uploadFile({
            url: getApp().BASE_URL + '/gr/uploadGrfileOne',
            filePath: imageSrc,
            name: 'image',
            header: {
              'content-type': 'application/x-www-form-urlencoded',
            },
            success(res) {

              
              var json = JSON.parse(res.data);
              console.log(res)
              that.setData({
                imagePathArray: that.data.imagePathArray.concat(json.data)
              })


              if (index == imageArray.length - 1) {
                // that.uploadVideo();
                that.uploadModel(model)

              }


            },
            fail() {
              wx.showToast({
                title: '上传错误，请重试',
                icon: 'none'
              })
              that.setData({
                imagePathArray: []
              })
            }
          })
        })(i)
      }
    } else {
      that.uploadModel(model)
    }



  },

  /**
   * 上传数据
   */
  uploadModel: function(model) {

    var that = this;
    var file = '';
    for (var i = 0; i < that.data.imagePathArray.length; i++) {
      file += that.data.imagePathArray;
      if (i != that.data.accompanyingArray.length - 1) {
        file += ',';
      }
    }
    model.file = file;
    wx.request({
      url: getApp().BASE_URL + '/gr/addGrPeople',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      method: 'POST',
      data: model,
      success: function(res) {
        console.log(res)
        if (res.data.code == 200) {
          wx.navigateTo({
            url: '/pages/personalSuccess/personalSuccess',
          })
        }
      },
      fail: function(res) {

      },
      complete: function(res) {
        wx.hideLoading();
      }
    })

  },

  /**
   * 显示信息
   */
  showErroMessage: function(mes) {
    wx.showToast({
      title: mes,
      icon: 'none',
      duration: 1500
    })
  }

})